/* The sidebar as a table of contents: five sections, one anatomy. Each card
   opens with a header row - gradient swatch + mono tag on the left, one pill
   action on the right, hairline below - so every block declares what it is
   and where it goes. The swatch colors match the destination pages' art. */

function SideSection({ art, glow, tag, action, onAction, pad = '18px 20px 18px', children }) {
  const { Button } = window.SevcikMarketingDesignSystem_3203fa;
  return (
    <section style={{ background: 'var(--white)', borderRadius: 'var(--radius-card)', overflow: 'hidden' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '13px 20px', borderBottom: '1.5px solid var(--gray-200)' }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <span aria-hidden="true" style={{ width: 13, height: 13, borderRadius: 4, background: art, display: 'block', flexShrink: 0, filter: glow ? `drop-shadow(0 0 7px ${glow})` : 'none' }} />
          <span className="sm-mono" style={{ fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 9.5, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--gray-500)' }}>{tag}</span>
        </span>
        {action && <Button variant="pill-light" size="xs" onClick={onAction} arrow>{action}</Button>}
      </div>
      <div style={{ padding: pad }}>{children}</div>
    </section>
  );
}

/* All logos in one draggable, slowly drifting loop - pauses on hover/drag. */
function LogoLoop({ logos }) {
  const ref = React.useRef(null);
  const st = React.useRef({ x: 0, drag: null, paused: false });
  React.useEffect(() => {
    const el = ref.current; if (!el) return;
    let raf;
    const step = () => {
      const s = st.current;
      if (!s.paused && !s.drag) s.x -= 0.08;
      const half = (el.scrollWidth / 2) || 1;
      if (s.x <= -half) s.x += half;
      if (s.x > 0) s.x -= half;
      el.style.transform = `translateX(${s.x}px)`;
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, []);
  return (
    <div style={{ overflow: 'hidden', cursor: 'grab', touchAction: 'pan-y' }}
      onPointerDown={(e) => { st.current.drag = { sx: e.clientX, x0: st.current.x }; e.currentTarget.setPointerCapture(e.pointerId); }}
      onPointerMove={(e) => { const d = st.current.drag; if (d) st.current.x = d.x0 + (e.clientX - d.sx); }}
      onPointerUp={() => { st.current.drag = null; }}
      onPointerCancel={() => { st.current.drag = null; }}
      onMouseEnter={() => { st.current.paused = true; }}
      onMouseLeave={() => { st.current.paused = false; }}>
      <div ref={ref} style={{ display: 'flex', alignItems: 'center', gap: 28, width: 'max-content' }}>
        {[...logos, ...logos].map((l, i) => (
          <img key={l.name + i} src={l.src} alt={i < logos.length ? l.name : ''} aria-hidden={i >= logos.length} draggable={false}
            style={{ height: Math.max(13, Math.round((l.h || 28) * 0.68)), width: 'auto', display: 'block', opacity: 0.6, flexShrink: 0, pointerEvents: 'none' }} />
        ))}
      </div>
    </div>
  );
}

/* One row per Services-page shape, same title and same gradient identity as
   the page it opens - a small round dot, not another square. */
function ShapeRow({ sec, last, onOpen }) {
  const [h, setH] = React.useState(false);
  const { Icon } = window.SevcikMarketingDesignSystem_3203fa;
  return (
    <div onClick={onOpen} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)} role="link" tabIndex={0}
      style={{ display: 'flex', alignItems: 'center', gap: 13, margin: '0 -12px', padding: '13px 12px', borderRadius: 8, cursor: 'pointer', borderBottom: last ? 'none' : '1.5px solid var(--gray-200)', background: h ? 'var(--gray-150)' : 'transparent', transition: 'background-color .25s ease' }}>
      <div style={{ minWidth: 0, flex: 1, transform: h ? 'translateX(3px)' : 'none', transition: 'transform .3s cubic-bezier(.22,1,.36,1)' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 16, lineHeight: 1.2, letterSpacing: '-0.01em', color: 'var(--black)' }}>{sec.title}</div>
        <div style={{ marginTop: 4, fontFamily: 'var(--font-meta)', fontWeight: 500, fontSize: 11.5, color: 'var(--gray-500)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{(sec.rows || []).map((r) => r[0]).slice(0, 3).join(' · ')}</div>
      </div>
      <span style={{ width: 28, height: 28, borderRadius: '50%', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: h ? 'var(--black)' : 'transparent', transition: 'background-color .25s ease' }}>
        <Icon name="arrow-up-right" size={13} color={h ? 'var(--white)' : 'var(--gray-400)'} />
      </span>
    </div>
  );
}

function PostMini({ post, last, onOpen }) {
  const [h, setH] = React.useState(false);
  return (
    <div onClick={() => onOpen(post)} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)} role="link" tabIndex={0}
      style={{ margin: '0 -12px', padding: '12px', borderRadius: 8, cursor: 'pointer', borderBottom: last ? 'none' : '1.5px solid var(--gray-200)', background: h ? 'var(--gray-150)' : 'transparent', transition: 'background-color .25s ease' }}>
      <div style={{ minWidth: 0, transform: h ? 'translateX(3px)' : 'none', transition: 'transform .3s cubic-bezier(.22,1,.36,1)' }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 9.5, lineHeight: 1.2, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--gray-500)' }}>{post.date}{post.read ? ` · ${post.read}` : ''}</div>
        <h3 style={{ margin: '6px 0 4px', fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 16, lineHeight: 1.25, letterSpacing: '-0.01em', color: 'var(--black)', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{post.title}</h3>
        <div style={{ fontFamily: 'var(--font-meta)', fontWeight: 500, fontSize: 12, lineHeight: 1.2, color: 'var(--gray-600)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{post.category}</div>
      </div>
    </div>
  );
}

/* One quiet line when a sidebar section has nothing published yet - the panel
   keeps its shape and its 'see all' button still opens the full explanation. */
function SideEmpty({ text }) {
  return (
    <p style={{ margin: 0, padding: '18px 0 22px', fontFamily: 'var(--font-body)', fontSize: 14.5, lineHeight: 1.6, color: 'var(--gray-500)' }}>{text}</p>
  );
}

function Sidebar({ s, t, lang, screen, onNavigate, onLangChange, menuOpen, onOpenArticle, onOpenCase }) {
  const { ProfileHeader, ProjectCard, Button } = window.SevcikMarketingDesignSystem_3203fa;
  const footerMeta = { fontFamily: 'var(--font-meta)', fontWeight: 500, fontSize: 12.5, lineHeight: 1.2, color: 'var(--gray-500)', margin: 0 };
  const footerMono = { fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 9.5, lineHeight: 1.45, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--gray-500)', margin: 0 };
  const quietLink = { fontFamily: 'var(--font-meta)', fontWeight: 500, fontSize: 14.5, lineHeight: 1.5, color: 'var(--gray-600)', textDecoration: 'none' };
  const shapes = s.servicesDetail.sections || [];
  return (
    <aside className="sm-sidebar" style={{ width: 'var(--sidebar-width)', flexShrink: 0, background: 'var(--paper)', padding: 10, display: 'flex', flexDirection: 'column', gap: 10, overflowY: 'auto', height: '100vh', boxSizing: 'border-box' }}>
      <div className="sm-side-profile" style={{ flexShrink: 0 }}><ProfileHeader lang={s.code} onLangChange={onLangChange} menuOpen={menuOpen} onMenuClick={() => onNavigate('menu')} whatsapp={CONTACT.whatsapp} links={{ linkedin: CONTACT.linkedin }} weekendsOff /></div>
      <div style={{ flexShrink: 0 }}>
        <SideSection art="var(--gradient-thumb-pastel)" glow="rgba(150,205,175,0.6)" tag={t.sideTags.intro} action={t.aboutMe} onAction={() => onNavigate('about')}>
          <p style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 400, fontSize: 14.5, lineHeight: 1.5, color: 'var(--black)' }}>{s.positioning}</p>
          <div style={{ marginTop: 18, paddingTop: 17, borderTop: '1.5px solid var(--gray-200)' }}>
            <LogoLoop logos={CLIENT_LOGOS} />
          </div>
        </SideSection>
      </div>
      <div style={{ flexShrink: 0 }}>
        <SideSection art="var(--gradient-thumb-cool)" glow="rgba(51,85,209,0.55)" tag={t.sideTags.services} action={t.servicesCta} onAction={() => onNavigate('services')} pad="6px 20px 8px">
          {shapes.map((sec, i) => (
            <ShapeRow key={sec.title} sec={sec} last={i === shapes.length - 1} onOpen={() => { window.__smServiceSection = i; onNavigate('services'); }} />
          ))}
        </SideSection>
      </div>
      <div style={{ flexShrink: 0 }}>
        <SideSection art="var(--gradient-thumb-pink)" glow="rgba(230,75,160,0.55)" tag={t.sideTags.reading} action={t.blogBtn} onAction={() => onNavigate('blog')} pad="6px 20px 8px">
          {s.posts.length === 0
            ? <SideEmpty text={t.emptySideArticles} />
            : s.posts.slice(0, 3).map((p, i) => (
              <PostMini key={p.id} post={p} last={i === Math.min(3, s.posts.length) - 1} onOpen={onOpenArticle} />
            ))}
        </SideSection>
      </div>
      <div style={{ flexShrink: 0 }}>
        <SideSection art="var(--orange-500)" glow="rgba(255,93,41,0.6)" tag={t.sideTags.contact}>
          <p style={{ margin: 0, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 19, lineHeight: 1.45, letterSpacing: '-0.01em', color: 'var(--black)' }}>{s.servicesDetail.ctaNote}</p>
          <div style={{ marginTop: 18, filter: 'drop-shadow(0 6px 18px rgba(255,93,41,0.38))' }}>
            <Button variant="cta" onClick={() => onNavigate('contact')} arrow>{t.bookCall}</Button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginTop: 18, paddingTop: 14, borderTop: '1.5px solid var(--gray-200)' }}>
            <a href={`mailto:${CONTACT.email}`} style={quietLink}>{CONTACT.email}</a>
            <a href={`tel:${CONTACT.phone.replace(/\s/g, '')}`} style={quietLink}>{CONTACT.phone}</a>
          </div>
        </SideSection>
      </div>
      <div style={{ flexShrink: 0 }}>
        <SideSection art="var(--gradient-thumb-warm)" glow="rgba(255,122,61,0.6)" tag={t.sideTags.cases} action={t.allBtn} onAction={() => onNavigate('cases')} pad="6px 20px 10px">
          {/* Every study is still under approval, so the titles are shown as a
             blurred hint of what is coming rather than as links that lead to
             an empty page. The section's own "all" button still works. */}
          {s.cases.length === 0
            ? <SideEmpty text={t.emptySideCases} />
            : (
              <div style={{ position: 'relative' }}>
                <div aria-hidden="true" inert="" style={{ filter: 'blur(5px)', opacity: 0.42, pointerEvents: 'none', userSelect: 'none' }}>
                  {s.cases.map((c, i) => (
                    <ProjectCard key={c.id} title={c.title} year={c.year} category={c.category} gradient={c.art} last={i === s.cases.length - 1} />
                  ))}
                </div>
                <p style={{ position: 'absolute', inset: 0, margin: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: '0 18px', fontFamily: 'var(--font-body)', fontSize: 14.5, lineHeight: 1.6, color: 'var(--gray-600)', textWrap: 'pretty' }}>{t.emptySideCases}</p>
              </div>
            )}
        </SideSection>
      </div>
      <div style={{ flexShrink: 0, borderRadius: 'var(--radius-card)', overflow: 'hidden', marginBottom: 10 }}>
        <div style={{ background: 'var(--white)', padding: '12px 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10 }}>
          <p style={footerMeta}>{s.siteName}</p>
          <p style={footerMono}>{new Date().toLocaleDateString(s.locale, { day: 'numeric', month: 'short' })}</p>
        </div>
        <div style={{ background: 'var(--white)', padding: '14px 20px', borderTop: '1.5px solid var(--gray-200)' }}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px 14px', marginBottom: 10 }}>
            {s.legal.links.map((l) => (
              <button key={l.screen} onClick={() => onNavigate(l.screen)} style={{ ...footerMono, background: 'none', border: 'none', padding: 0, cursor: 'pointer' }}
                onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--orange-600)'; }} onMouseLeave={(e) => { e.currentTarget.style.color = ''; }}>{l.label}</button>
            ))}
          </div>
          <p style={footerMono}>© {new Date().getFullYear()} {s.siteName} · {s.footerRights}</p>
        </div>
      </div>
    </aside>
  );
}

Object.assign(window, { Sidebar });
